import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

// create an axios instance
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
request.interceptors.request.use(function (config) {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = token
  }
  return config
},
  function (err) {
    return Promise.reject(err)
  }
)

// response interceptor
request.interceptors.response.use(function (response) {
  if (response.data.msg !== 'ok') {
    Message.error(response.data.msg)
    return Promise.reject(new Error(response.data.msg))
  } else {
    return response.data.data
  }
}, function (err) {
  Message.error(err.response.data)
  return Promise.reject(err)
})

export default request

